import { defineStore } from "pinia";
import { getRouters } from "@/api/admin/system/menu";
import dynamicRouter from "@/router/dynamicRouter";
import { removeToken } from "@/utils/auth";
import { RouteRecordRaw } from "vue-router";
import { IMenu } from "@/api/admin/system/menu/type";

// 遍历后台传来的路由，生成路由
function filterAsyncRouter(asyncRouterMap: IMenu[]) {
  // 过滤类型为方法的列表
  asyncRouterMap = asyncRouterMap.filter(
    (item: IMenu) => item.menu_type !== "F"
  );
  const routesObj: any = {};
  asyncRouterMap.forEach((item: IMenu) => {
    item.children = [];
    item.component = dynamicRouter[item.component];
    routesObj[item.id] = item;
  });
  const routes: any = [];
  const menus: any = [];
  asyncRouterMap.forEach((list: any) => {
    const obj = {
      path: list.path,
      name: list.name,
      component: list.component,
      hidden: list.visible !== "1",
      children: list.children,
      meta: {
        title: list.title,
        menu_type: list.menu_type,
        is_frame: list.is_frame, // 外链
        cache: list.keep_alive === "1" ? true : false, // 不缓存
        icon: list.icon,
      },
    };
    if (list.parent_id !== 0) {
      routesObj[list.parent_id].children.push(obj);
    } else {
      if (list.path.indexOf("/layout") !== -1) {
        routes.push({
          path: list.path,
          // name: list.name,
          component: dynamicRouter.Layout,
          hidden: list.visible !== "1",
          children: [obj],
          meta: {
            title: list.title,
            is_frame: list.is_frame, // 外链
            cache: list.keep_alive === "1" ? true : false, // 不缓存
            icon: list.icon,
          },
        });
      } else {
        routes.push(obj);
      }
      menus.push(obj);
    }
  });
  return {
    routes,
    menus,
    routesObj,
  };
}

interface PermissionStore {
  routes: RouteRecordRaw[];
  sidebarRouters: RouteRecordRaw[];
}

export const usePermissionStore = defineStore({
  id: "permission",
  state: (): PermissionStore => {
    return {
      routes: [],
      sidebarRouters: [],
    };
  },
  getters: {},
  actions: {
    // 生成路由
    async GenerateRoutes() {
      try {
        const res = await getRouters();
        const { routes: accessedRoutes, menus: accessedMenus } =
          filterAsyncRouter(res.data.lists);
        accessedRoutes.push({
          path: "/:catchAll(.*)",
          redirect: "/404",
          hidden: true,
        });
        this.sidebarRouters = accessedMenus;
        this.routes = accessedRoutes;
        return accessedRoutes;
      } catch (error: any) {
        console.log(error);
        if (error.response.status === 401) {
          removeToken();
        }
      }
    },
  },
});
